package com.wngbms._05.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.concurrent.EventExecutorGroup;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;

public class HttpHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        String uri = fullHttpRequest.uri();
        handleTest(fullHttpRequest, ctx);
    }

    private void handleTest(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) {
        System.out.println("handle");
        FullHttpResponse response = null;
        String body = "Windows 11";
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(body.getBytes(StandardCharsets.UTF_8)));
        response.headers().set("Content-Type", "text/html");
        response.headers().set("Content-Length", response.content().readableBytes());

        if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
//            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.writeAndFlush(response);
//            ctx.write(response);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }
}
